﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Management;

namespace Light.Utility
{
    /// <summary>
    /// CPU监视器
    /// </summary>
    public class CpuMonitor
    {

        ManagementScope scope;
        ConnectionOptions options = new ConnectionOptions();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="hostIP">目标主机</param>
        /// <param name="userName">主机登录名</param>
        /// <param name="password">主机登录密码</param>
        public CpuMonitor(string hostIP, string userName, string password)
        {
            options.Username = userName;
            options.Password = password;

            scope = new ManagementScope("\\\\" + hostIP + "\\root\\cimv2", options);
        }


        /// <summary>
        /// 获取主机CPU的使用状态
        /// </summary>
        /// <returns></returns>
        public string GetCpuState()
        {
            string percentage = "";
            try
            {
                scope.Connect();
            }
            catch (Exception ex)
            {
                //return ex.Message;
                return "-1";
            }

            //Query system for Operating System information
            ObjectQuery query = new ObjectQuery("select * from Win32_Processor");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

            ManagementObjectCollection queryCollection = searcher.Get();
            foreach (ManagementObject m in queryCollection)
            {
                percentage = m["LoadPercentage"].ToString();
            }
            return percentage;
        }
    }
}
